<script setup>
//弹窗的默认
import { ref } from 'vue'
import { artEditChannelService, artAddChannelService } from '@/api/article'
const dialogVisible = ref(false)
const formref = ref()
const formModol = ref({
  cate_name: '',
  cate_alias: ''
})
//组件对外暴漏方法 open 基于open传来的参数去区分添加还是编辑
// open({}) => 表单无需渲染 说明是添加
// open({id:1,cate_name,...}) => 表单需要渲染 说明是编辑
// open调用后可以去打开弹窗
const open = (row) => {
  dialogVisible.value = true
  formModol.value = { ...row } //如果是添加相当于是重置了表单内容 如果是编辑就相当于存储了我们需要回显的数据
}

//向外暴漏
defineExpose({ open })

//校验
const rules = {
  cate_name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    {
      pattern: /^\S{1,10}$/,
      message: '分类名必须是1-10位的非空字符',
      trigger: 'blur'
    }
  ],
  cate_alias: [
    { required: true, message: '请输入分类别名', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9]{1,15}$/,
      message: '分类名必须1-15位的字母或数字',
      trigger: 'blur'
    }
  ]
}
const emit = defineEmits(['success'])
const onsubmit = async () => {
  await formref.value.validate()
  const isEdit = formModol.value.id
  if (isEdit) {
    await artEditChannelService(formModol.value)
    ElMessage.success('编辑成功')
  } else {
    await artAddChannelService(formModol.value)
    ElMessage.success('添加成功')
  }
  dialogVisible.value = false
  emit('success')
}
</script>
<template>
  <el-dialog
    v-model="dialogVisible"
    :title="formModol.id ? '编辑分类' : '添加分类'"
    width="30%"
  >
    <el-form
      :hide-required-asterisk="true"
      ref="formref"
      :model="formModol"
      :rules="rules"
      label-width="100px"
      style="padding-right: 30px"
    >
      <el-form-item label="分类名称" prop="cate_name">
        <el-input
          v-model="formModol.cate_name"
          placeholder="请输入分类名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="分类别名" prop="cate_alias">
        <el-input
          v-model="formModol.cate_alias"
          placeholder="请输入分类别名"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onsubmit"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>
</template>
